package com.cloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
//服务发现

/**
 * http://localhost:8081/instances
 *
 */
@RestController
@Slf4j
public class ConsumerController {

    //会自动装载
    @Autowired
    private DiscoveryClient discoveryClient;

    //不会自动装载 需要配置
    @Autowired
    private RestTemplate restTemplate;


    @GetMapping("/instances")
    public List<ServiceInstance> instances(){
        List<ServiceInstance> provider = this.discoveryClient.getInstances("provider");
        return provider;
    }

    // 调用provider的index方法
    //微服务调用
    //http://localhost:8081/index
    //增加Ribbon注解后这种调用失效
    @GetMapping("/index")
    public String index(){
        List<ServiceInstance> provider = discoveryClient.getInstances("provider");
        int index = ThreadLocalRandom.current().nextInt(provider.size());
        ServiceInstance serviceInstance = provider.get(index);
        String url = provider.get(index).getUri()+"/index";
        log.info("得到的url是{}", url);
        log.info("调用的端口是：{}", serviceInstance.getPort());
        return "consumer随机远程调用provier："+this.restTemplate.getForObject(url, String.class);
    }

    //通过Ribbon做负载均衡之后调用Ribbon
    //http:localhost:8081/ribbonIndex
    @GetMapping("/ribbonIndex")
    public String ribbonIndex() {
        return this.restTemplate.getForObject("http://provider/index", String.class);
    }

}
